(ns tala.rdf
  (:import org.mulgara.mrg.GraphImpl
           org.mulgara.mrg.Uri
           org.mulgara.mrg.Literal
           org.mulgara.mrg.SubjectNode
           org.mulgara.mrg.PredicateNode
           org.mulgara.mrg.ObjectNode
           org.mulgara.mrg.vocab.RDF
           org.mulgara.mrg.vocab.FOAF))

;; SEQ->GRAPH : sequence -> Graph
;; Given a sequence of three-element vectors, return a new graph
;; composed of the triples those vectors represent.
;; The subject   may be a SubjectNode or a URI;
;; The predicate may be a PredicateNode, a URI, or ':a' to indicate RDF/TYPE;
;; The literal   may be a ObjectNode (Uri or Literal), a URI, or a string? to indicate a literal string.
(defn make-simple-graph [triples]
  (reduce (fn [g trips]
            (.insert g
                     (let [s (trips 0)]
                       (cond (instance? SubjectNode s) s
                             (instance? java.net.URI s) (Uri. s)
                             :else (throw (IllegalArgumentException.
                                           (str "make-simple-graph must have a URI or SubjectNode as subject, not " s)))))
                     (let [p (trips 1)]
                       (cond (instance? PredicateNode p) p
                             (instance? java.net.URI p) (Uri. p)
                             (= p :a) RDF/TYPE
                             :else (throw (IllegalArgumentException.
                                           (str "make-simple-graph must have :a or PredicateNode as predicate argument, not " p)))))
                     (let [o (trips 2)]
                       (cond (instance? ObjectNode o) o
                             (instance? java.net.URI o) (Uri. o)
                             (string? o) (Literal. o)
                             :else (throw (IllegalArgumentException.
                                           (str "make-simple-graph must have a string or ObjectNode object, not " o))))))
            g)
          (GraphImpl.)
          triples))

;; Call with 'lein run -m tala.rdf [args...]'
;; (defn -main [& args]
;;   (println "Hello there! (rdf): " args)
;;   (let [n (Uri. "http://nxg.me.uk/norman/")]
;;     (.exportN3 (make-simple-graph (lazy-seq [[n RDF/TYPE FOAF/PERSON]
;;                                              [n FOAF/NAME (Literal. "Norman")]]))
;;                System/out)))
